<template>
    <el-dialog title="查看物料需求表" :visible.sync="dialogVisible" width="1000px" @close="handleClose" append-to-body
        modal-append-to-body>
        <el-table v-loading="loading" :data="materialList" @selection-change="handleSelectionChange" border stripe>
            
            <el-table-column label="物料编码" align="center" prop="materialCode" width="140" />
            <el-table-column label="物料名称" align="center" prop="materialName" width="120" />
            <el-table-column label="规格" align="center" prop="specification" width="100" />
            <el-table-column label="供应商" align="center" prop="supplier" width="140" />
            <el-table-column label="生产厂家" align="center" prop="manufacturer" width="140" />
            <el-table-column label="厂家批号" align="center" prop="manufacturerBatchNumber" width="120" />
            <el-table-column label="收货日期" align="center" prop="receiptDate" width="120" />
            <el-table-column label="有效期至" align="center" prop="expirationDate" width="120">
                <template slot-scope="scope">
                    <span :class="{ 'text-red': isExpired(scope.row.expirationDate) }">
                        {{ scope.row.expirationDate }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column label="存储条件" align="center" prop="storageCondition" width="100" />
            <el-table-column label="合格数量" align="center" prop="qualifiedQuantity" width="100" />
            <el-table-column label="收货状态" align="center" prop="receiptStatus" width="100">
                <template slot-scope="scope">
                    <el-tag :type="getStatusTagType(scope.row.receiptStatus)">
                        {{ getReceiptStatusText(scope.row.receiptStatus) }}
                    </el-tag>
                </template>
            </el-table-column>
        </el-table>

    
    </el-dialog>
</template>

<script>
import { getMaterialByCode } from "@/api/material/MaterialRecord";

export default {
    name: "MaterialSelectDialog",
    props: {
        // 接收父组件传递的物料编码，支持单个或多个（逗号分隔）
        materialCode: {
            type: String,
            default: "",
        },
    },
    data() {
        return {
            dialogVisible: false,
            loading: false,
            materialList: [], // 存储查询到的物料列表
            selectedMaterials: [],
            receiptStatusMap: {
                1: "待验收",
                2: "已验收",
                3: "已拒收",
            },
            statusTagTypeMap: {
                1: "info",
                2: "success",
                3: "danger",
            },
        };
    },
    methods: {
        // 按物料编码查询
        // 按物料编码查询，code参数可选，默认使用props中的materialCode
        getMaterialByCodeList(code = this.materialCode) {
            // 校验物料编码是否存在
            if (!code.trim()) {
                this.$message.warning("物料编码不能为空");
                return;
            }

            this.loading = true;
            getMaterialByCode(code.trim())
                .then((response) => {
                    const result = response.data || [];
                    if (result.length === 0) {
                        this.$message.info("未查询到对应物料编码的记录");
                        this.materialList = [];
                    } else {
                        this.materialList = result;
                    }
                })
                .catch((error) => {
                    console.error("按编码查询物料失败：", error);
                    this.$message.error("查询物料失败，请稍后重试");
                })
                .finally(() => {
                    this.loading = false;
                });
        },
        // 选中物料变化
        handleSelectionChange(selection) {
            this.selectedMaterials = selection;
        },
        // 确认选择
        confirmSelection() {
            if (this.selectedMaterials.length === 0) {
                this.$message.warning("请选择至少一个物料");
                return;
            }
            this.$emit("material-selected", this.selectedMaterials);
            this.dialogVisible = false;
        },
        // 关闭对话框
        handleClose() {
            this.$emit("dialog-closed");
            this.selectedMaterials = [];
        },
        // 显示对话框，同时调用查询接口
        show() {
            this.dialogVisible = true;
            this.$nextTick(() => {
                this.getMaterialByCodeList();
            });
        },
        // 判断物料是否过期
        isExpired(expirationDate) {
            if (!expirationDate) return false;
            const expireDate = new Date(expirationDate);
            const today = new Date();
            expireDate.setHours(0, 0, 0, 0);
            today.setHours(0, 0, 0, 0);
            const daysDiff = Math.ceil((expireDate - today) / (1000 * 60 * 60 * 24));
            return daysDiff <= 0 || daysDiff <= 7;
        },
        // 获取收货状态文本
        getReceiptStatusText(status) {
            return this.receiptStatusMap[status] || `未知状态(${status})`;
        },
        // 获取收货状态标签类型
        getStatusTagType(status) {
            return this.statusTagTypeMap[status] || "default";
        },
    },
};
</script>


<style scoped>
.el-dialog {
    z-index: 3000 !important;
    /* 提高层级，确保在其他元素之上 */
}

/* 新增：过期/即将过期文字样式 */
.text-red {
    color: #F56C6C;
    font-weight: 500;
}

/* 优化表格样式：表头背景色 */
.el-table th {
    background-color: #F5F7FA !important;
}
</style>